/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved.
 */
package com.icinfo.cloud.provider.punish.execute.service.impl;

import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.enums.LimitDayTypeEnum;
import com.icinfo.cloud.provider.common.enums.YesOrNoEnum;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.punish.approval.constant.AuditStatusConstant;
import com.icinfo.cloud.provider.punish.approval.dto.AuditDetailDocumentQueryDto;
import com.icinfo.cloud.provider.punish.approval.mapper.CaseApprovalCompleteRecordMapper;
import com.icinfo.cloud.provider.punish.approval.mapper.CaseApprovalFlowRelationMapper;
import com.icinfo.cloud.provider.punish.approval.mapper.CaseApprovalWaitRecordMapper;
import com.icinfo.cloud.provider.punish.approval.model.CaseApprovalCompleteRecord;
import com.icinfo.cloud.provider.punish.approval.model.CaseApprovalFlowRelation;
import com.icinfo.cloud.provider.punish.approval.model.CaseApprovalWaitRecord;
import com.icinfo.cloud.provider.punish.approval.service.impl.CaseApprovalCompleteRecordServiceImpl;
import com.icinfo.cloud.provider.punish.approval.vo.AuditInfoChainLogTopVo;
import com.icinfo.cloud.provider.punish.approval.vo.AuditInfoChainLogVo;
import com.icinfo.cloud.provider.punish.common.documentoperate.enums.DocumentRecordStatusEnum;
import com.icinfo.cloud.provider.punish.common.documentoperate.enums.DocumentStatusEnum;
import com.icinfo.cloud.provider.punish.common.electricsent.enums.DocumentSendStatusEnum;
import com.icinfo.cloud.provider.punish.config.dto.ConfigEndDayQueryDto;
import com.icinfo.cloud.provider.punish.config.model.ConfigBusiParamDocumentInfo;
import com.icinfo.cloud.provider.punish.config.service.IConfigBusiParamDocumentInfoService;
import com.icinfo.cloud.provider.punish.config.service.IConfigWorkRestDayInfoService;
import com.icinfo.cloud.provider.punish.csource.manage.model.CaseSourceDocumentRecord;
import com.icinfo.cloud.provider.punish.execute.dto.ExecuteDocumentRecordDelDto;
import com.icinfo.cloud.provider.punish.execute.dto.ExecuteDocumentRecordDto;
import com.icinfo.cloud.provider.punish.execute.dto.ExecuteStageLinkRelateDocumentQueryDto;
import com.icinfo.cloud.provider.punish.execute.mapper.ExecuteDocumentRecordHisMapper;
import com.icinfo.cloud.provider.punish.execute.mapper.ExecuteDocumentRecordMapper;
import com.icinfo.cloud.provider.punish.execute.model.ExecuteDocumentRecord;
import com.icinfo.cloud.provider.punish.execute.model.ExecuteDocumentRecordHis;
import com.icinfo.cloud.provider.punish.execute.service.IExecuteDocumentRecordService;
import com.icinfo.cloud.provider.punish.execute.vo.ExecuteDocumentRecordVo;
import com.icinfo.cloud.provider.punish.execute.vo.ExecuteStageLinkRelateDocumentVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseDocumentRecord;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import com.icinfo.framework.tools.utils.DateUtils;
import com.icinfo.framework.tools.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 描述: 裁执分离文书记录表 execute_document_record 对应的Service接口实现类.<br>
 *
 * @author framework generator
 * @date 2022年08月26日
 */
@Service
public class ExecuteDocumentRecordServiceImpl extends MyBatisServiceSupport implements IExecuteDocumentRecordService {
    /**
     * 日志记录器
     */
    private static final Logger logger = LoggerFactory.getLogger(ExecuteDocumentRecordServiceImpl.class);

    @Resource
    private ExecuteDocumentRecordMapper executeDocumentRecordMapper;
    @Resource
    private ExecuteDocumentRecordHisMapper executeDocumentRecordHisMapper;
    @Resource
    private IConfigBusiParamDocumentInfoService configBusiParamDocumentInfoService;
    @Resource
    private CaseApprovalCompleteRecordServiceImpl caseApprovalCompleteRecordService;
    @Resource
    private IConfigWorkRestDayInfoService configWorkRestDayInfoService;

    @Resource
    private CaseApprovalWaitRecordMapper caseApprovalWaitRecordMapper;

    @Resource
    private CaseApprovalFlowRelationMapper caseApprovalFlowRelationMapper;

    @Resource
    private CaseApprovalCompleteRecordMapper caseApprovalCompleteRecordMapper;

    @Override
    public List<ExecuteStageLinkRelateDocumentVo> getExecuteStageLinkRelateDocumentInfo(ExecuteStageLinkRelateDocumentQueryDto query) {
        List<ExecuteStageLinkRelateDocumentVo> executeStageLinkRelateDocumentList
                = executeDocumentRecordMapper.selectExecuteStageLinkRelateDocumentInfo(query);

        Set<String> set = new HashSet<>();
        Iterator<ExecuteStageLinkRelateDocumentVo> iterator = executeStageLinkRelateDocumentList.iterator();
        while (iterator.hasNext()) {
            ExecuteStageLinkRelateDocumentVo e = iterator.next();
            //非草稿状态的文书设置相关状态的名称
            if (!DocumentRecordStatusEnum.DRAFT.getCode().equals(e.getDocumentRecordStatus())) {
                e.setDocumentApprovalStatusName(DocumentStatusEnum.getValueByCode(e.getDocumentApprovalStatus()));
                e.setDocumentSentStatusName(DocumentStatusEnum.getValueByCode(e.getDocumentSentStatus()));
                e.setDocumentSignstampedStatusName(DocumentStatusEnum.getValueByCode(e.getDocumentSignstampedStatus()));
            }
            e.setDocumentRecordStatusName(DocumentRecordStatusEnum.getValueByCode(e.getDocumentRecordStatus()));
            //update
            if (StringUtils.isNotEmpty(e.getDocumentUrlAfterSeal())) {
                e.setDocumentUrl(e.getDocumentUrlAfterSeal());
            }
            if (StringUtils.isNotEmpty(e.getDocumentUrlAfterSign())) {
                e.setDocumentUrl(e.getDocumentUrlAfterSign());
            }
            String documentKindCode = e.getDocumentKindCode();
            if (Constant.STRING_KIND_CODE_ZXQKHCJL.equals(documentKindCode)) {
                String kindCode = e.getDocumentKindCode();
                String partyId = e.getPartyId();
                String combineInfo = kindCode + "_" + partyId;
                if (set.contains(combineInfo)) {
                    iterator.remove();
                } else {
                    set.add(combineInfo);
                }
            }
        }
        return executeStageLinkRelateDocumentList;
    }

    /**
     * 查询案源文书
     *
     * @param executeId
     * @param documentCatalogCode
     * @param partyId
     * @return {@link CaseSourceDocumentRecord}
     * @author wuzhihui
     * @date 2022/8/29
     */
    @Override
    public ExecuteDocumentRecord getExecuteDocumentRecord(String executeId, String documentCatalogCode, String partyId) {
        //查询文书记录数据
        Example example = new Example(ExecuteDocumentRecord.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("executeId", executeId).andEqualTo("documentCatalogCode", documentCatalogCode)
                //.andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
                .andIn("documentRecordStatus", Arrays.asList(DocumentRecordStatusEnum.NORMAL.getCode(), DocumentRecordStatusEnum.DRAFT.getCode()));
        if (!ObjectUtils.isEmpty(partyId)) {
            criteria.andEqualTo("partyId", partyId);
        }
        List<ExecuteDocumentRecord> executeDocumentRecords = executeDocumentRecordMapper.selectByExample(example);
        if (executeDocumentRecords == null || executeDocumentRecords.size() == 0) {
            return null;
        }
        return executeDocumentRecords.get(0);
    }

    @Override
    public int delExecuteDocumentRecordInfo(ExecuteDocumentRecordDelDto delDto) {
        String partyId = delDto.getPartyId();
        String executeId = delDto.getExecuteId();

        String documentId = delDto.getDocumentId();
        List<ExecuteDocumentRecord> executeDocumentRecordList = new ArrayList();
        ExecuteDocumentRecord executeDocumentRecord = executeDocumentRecordMapper.selectByPrimaryKey(documentId);
        if (ObjectUtils.isEmpty(executeDocumentRecord)) {
            throw new BusinessException("文书不存在");
        }
        executeDocumentRecordList.add(executeDocumentRecord);
        //不为空，则添加历史，删除记录
        int num = deleteAndSaveHis(executeDocumentRecordList);
        executeDocumentRecordMapper.deleteByPrimaryKey(delDto.getDocumentId());

        //查询关联文书
        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(executeDocumentRecord.getDocumentCatalogCode());
        String relateCode = configBusiParamDocumentInfo.getRelationDocumentCatalogCode();
        if (StringUtils.isNotBlank(relateCode)) {
            String[] relateCodeArr = relateCode.split(",");
            for (String relateCodeStr : relateCodeArr) {
                //todo 删除暂存内容 暂时没有暂存

                //查询文书记录数据
                Example relateExample = new Example(ExecuteDocumentRecord.class);
                relateExample.createCriteria().andEqualTo("executeId", executeId)
                        .andEqualTo("documentCatalogCode", relateCodeStr)
                        .andEqualTo("partyId", partyId)
                        //.andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
                        .andIn("documentRecordStatus", Arrays.asList(DocumentRecordStatusEnum.NORMAL.getCode(), DocumentRecordStatusEnum.DRAFT.getCode()));
                List<ExecuteDocumentRecord> relateExecuteDocumentRecords = executeDocumentRecordMapper.selectByExample(relateExample);
                if (null != relateExecuteDocumentRecords && relateExecuteDocumentRecords.size() > 0) {
                    //删除当前环节附件
                    num = deleteAndSaveHis(relateExecuteDocumentRecords);

                }

            }
        }
        return num;
    }

    @Override
    public AuditInfoChainLogTopVo getAuditChainTop(AuditDetailDocumentQueryDto auditDetailDocumentQueryDto) {
        String caseId = auditDetailDocumentQueryDto.getCaseId();
        String documentCatalogCode = auditDetailDocumentQueryDto.getDocumentCatalogCode();
        String pass = "pass";
        String rtn = "return";
        String ns = "notSubmit";
        // 当前文书审批状态
        Example exampleDocRed = new Example(ExecuteDocumentRecord.class);
        exampleDocRed.createCriteria().andEqualTo("executeId", caseId)
                .andEqualTo("documentCatalogCode", documentCatalogCode)
                //.andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
                .andIn("documentRecordStatus", Arrays.asList(DocumentRecordStatusEnum.NORMAL.getCode(), DocumentRecordStatusEnum.DRAFT.getCode()));
        List<ExecuteDocumentRecord> executeDocumentRecords = executeDocumentRecordMapper.selectByExample(exampleDocRed);
        if (executeDocumentRecords.isEmpty()) {
            throw new BusinessException("未匹配到文书记录");
        }
        ExecuteDocumentRecord executeDocumentRecord = executeDocumentRecords.get(0);
        // 审批完成，添加最后节点信息
        AuditInfoChainLogTopVo vo = new AuditInfoChainLogTopVo();
        // 未提交没有头部
        if (StringUtils.isBlank(executeDocumentRecord.getDocumentAuditStatus()) || ns.equals(executeDocumentRecord.getDocumentAuditStatus())) {
            return vo;
        }
        // 审批中头部
        // 查询待审核记录
        Example exampleWait = new Example(CaseApprovalWaitRecord.class);
        exampleWait.createCriteria().andEqualTo("caseId", caseId)
                .andEqualTo("documentId", documentCatalogCode);
        List<CaseApprovalWaitRecord> caseApprovalWaitRecords = caseApprovalWaitRecordMapper.selectByExample(exampleWait);
        if (!caseApprovalWaitRecords.isEmpty()) {
            CaseApprovalFlowRelation caseApprovalFlowRelation = caseApprovalFlowRelationMapper.selectByPrimaryKey(caseApprovalWaitRecords.get(0).getFlowRelationId());
            vo.setStageName(caseApprovalFlowRelation.getApprovalRoleName());
            vo.setDeadlineDate(DateUtils.formatDate(caseApprovalWaitRecords.get(0).getApprovalCurrentPlanendTime(), "yyyy-MM-dd"));
            //截止时间- 当前时间
            vo.setRemainTime(caseApprovalCompleteRecordService.getDateTimeString(new Date(), caseApprovalWaitRecords.get(0).getApprovalCurrentPlanendTime(), "YES"));
            return vo;
        }
        Example exampleComplete = new Example(CaseApprovalCompleteRecord.class);
        exampleComplete.createCriteria().andEqualTo("caseId", caseId)
                .andEqualTo("documentId", documentCatalogCode);
        exampleComplete.orderBy("approvalNum").asc();
        List<CaseApprovalCompleteRecord> caseApprovalCompleteRecords = caseApprovalCompleteRecordMapper.selectByExample(exampleComplete);
        if (caseApprovalCompleteRecords.isEmpty()) {
            return vo;
        }
        // 最后审核时间-提交时间
        Date date1 = caseApprovalCompleteRecords.get(0).getAddTime();
        Date date2 = caseApprovalCompleteRecords.get(caseApprovalCompleteRecords.size() - 1).getApprovalTime();
        String costAllTime = caseApprovalCompleteRecordService.getDateTimeString(date1, date2, null);
        //审批完成头部
        if (pass.equals(executeDocumentRecord.getDocumentAuditStatus())) {
            vo.setStageName("审批通过");
            vo.setRemainTime(costAllTime);
        }
        if (rtn.equals(executeDocumentRecord.getDocumentAuditStatus())) {
            vo.setStageName("审批退回");
            vo.setRemainTime(costAllTime);
        }
        return vo;
    }

    @Override
    public List<AuditInfoChainLogVo> getAuditChain(AuditDetailDocumentQueryDto auditDetailDocumentQueryDto) throws ParseException {
        String caseId = auditDetailDocumentQueryDto.getCaseId();
        String documentCatalogCode = auditDetailDocumentQueryDto.getDocumentCatalogCode();
        List<AuditInfoChainLogVo> result = new ArrayList<>();
        // 查询发起人节点
        // 当前文书审批状态
        Example exampleDocRed = new Example(ExecuteDocumentRecord.class);
        exampleDocRed.createCriteria().andEqualTo("executeId", caseId)
                .andEqualTo("documentCatalogCode", documentCatalogCode)
                //.andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
                .andIn("documentRecordStatus", Arrays.asList(DocumentRecordStatusEnum.NORMAL.getCode(), DocumentRecordStatusEnum.DRAFT.getCode()));
        List<ExecuteDocumentRecord> executeDocumentRecords = executeDocumentRecordMapper.selectByExample(exampleDocRed);
        if (executeDocumentRecords.isEmpty()) {
            throw new BusinessException("未匹配到文书记录");
        }
        ExecuteDocumentRecord executeDocumentRecord = executeDocumentRecords.get(0);
        // 发起人节点
        AuditInfoChainLogVo first = new AuditInfoChainLogVo();
        first.setStageName("发起申请");
        // 查询已审核记录
        Example exampleComplete = new Example(CaseApprovalCompleteRecord.class);
        exampleComplete.createCriteria().andEqualTo("caseId", caseId)
                .andEqualTo("documentId", documentCatalogCode).andNotEqualTo("approvalStatus", AuditStatusConstant.AUDIT_STATUS_RECALL);
        exampleComplete.orderBy("approvalTime").asc();
        exampleComplete.orderBy("approvalNum").asc();
        List<CaseApprovalCompleteRecord> caseApprovalCompleteRecords = caseApprovalCompleteRecordMapper.selectByExample(exampleComplete);
        // 查询待审核记录
        Example exampleWait = new Example(CaseApprovalWaitRecord.class);
        exampleWait.createCriteria().andEqualTo("caseId", caseId).andEqualTo("documentId", documentCatalogCode);
        List<CaseApprovalWaitRecord> caseApprovalWaitRecords = caseApprovalWaitRecordMapper.selectByExample(exampleWait);
        if (caseApprovalWaitRecords.isEmpty() && caseApprovalCompleteRecords.isEmpty()) {
            return result;
        }
        // pending  审批中  ，pass 审核完成通过，return 审核完成退回
        String pending = "pending";
        // 未提交状态
        String ns = "notSubmit";
        // 未提交不显示审批链
        if (StringUtils.isBlank(executeDocumentRecord.getDocumentAuditStatus()) || ns.equals(executeDocumentRecord.getDocumentAuditStatus())) {
            return result;
        }
        // 生成发起人节点
        caseApprovalCompleteRecordService.setFirstChainNode(result, first, caseApprovalCompleteRecords, caseApprovalWaitRecords,documentCatalogCode);
        Example exampleRelation = new Example(CaseApprovalFlowRelation.class);
        exampleRelation.createCriteria().andEqualTo("documentCatalogCode", documentCatalogCode).andEqualTo("isNowVersion", "1");
        List<CaseApprovalFlowRelation> caseApprovalFlowRelations = caseApprovalFlowRelationMapper.selectByExample(exampleRelation);
        if (StringUtils.isBlank(executeDocumentRecord.getDocumentAuditStatus()) || ns.equals(executeDocumentRecord.getDocumentAuditStatus())) {
            for (CaseApprovalFlowRelation relation : caseApprovalFlowRelations) {
                AuditInfoChainLogVo vo = new AuditInfoChainLogVo();
                vo.setStageName(relation.getApprovalRoleName());
                vo.setIsAudit("NO");
                vo.setIsOwnAudit("NO");
                result.add(vo);
            }
            return result;
        }
        // 拼接已审核节点
        caseApprovalCompleteRecordService.setAlreadyNodes(result, caseApprovalCompleteRecords,auditDetailDocumentQueryDto.getDocumentCatalogCode());
        //审批中
        if (pending.equals(executeDocumentRecord.getDocumentAuditStatus())) {
            AuditInfoChainLogVo vo = new AuditInfoChainLogVo();
            vo.setStageName("等待审批");
            vo.setPersonName(caseApprovalWaitRecords.get(0).getApprovalUserName());
            vo.setIsAudit("NO");
            vo.setIsOwnAudit("NO");
            // 当前待审核人是否是当前用户
            UserDTO userDTO = UserUtil.getUserInfo();
            if (userDTO.getUserId().toString().equals(caseApprovalWaitRecords.get(0).getApprovalUserId())) {
                vo.setIsOwnAudit("YES");
            }
            // 环节时长
            String lastNodeAuditTime = result.get(result.size() - 1).getAuditTime();
            Date lastNodeAuditDate = DateUtils.parseDate(lastNodeAuditTime, "yyyy-MM-dd HH:mm:ss");
            String costTime = caseApprovalCompleteRecordService.getDateTimeString(lastNodeAuditDate, new Date(), null);
            vo.setCurrentCostTime(costTime);
            result.add(vo);
            //拼接未指定审批人节点
            exampleRelation.clear();
            CaseApprovalFlowRelation caseApprovalFlowRelation = caseApprovalFlowRelationMapper.selectByPrimaryKey(caseApprovalWaitRecords.get(0).getFlowRelationId());
            if (caseApprovalFlowRelation == null) {
                logger.error("未匹配到文书记录-getAuditChain,caseId:{},documentCatalogCode:{}", caseId, documentCatalogCode);
                throw new BusinessException("未匹配到文书记录-getAuditChain");
            }
            // 查询未审核配置信息
            exampleRelation.createCriteria().andEqualTo("documentCatalogCode", documentCatalogCode).
                    andEqualTo("approvalFlowId", caseApprovalFlowRelation.getApprovalFlowId()).
                    andEqualTo("approvalFlowVerson", caseApprovalFlowRelation.getApprovalFlowVerson()).andGreaterThan("approvalOrderNum", caseApprovalWaitRecords.get(0).getApprovalNum());
            exampleRelation.orderBy("approvalOrderNum").asc();
            caseApprovalFlowRelations = caseApprovalFlowRelationMapper.selectByExample(exampleRelation);
            for (CaseApprovalFlowRelation relation : caseApprovalFlowRelations) {
                AuditInfoChainLogVo noAppointNode = new AuditInfoChainLogVo();
                noAppointNode.setStageName(relation.getApprovalRoleName());
                noAppointNode.setIsAudit("NO");
                noAppointNode.setIsOwnAudit("NO");
                result.add(noAppointNode);
            }
            return result;
        }
        return result;
    }

    @Override
    public ExecuteDocumentRecordVo getExecuteDocumentRecordInfo(String documentId) {
        ExecuteDocumentRecord executeDocumentRecord = executeDocumentRecordMapper.selectByPrimaryKey(documentId);
        if (ObjectUtils.isEmpty(executeDocumentRecord)) {
            throw new BusinessException("未匹配到文书记录");
        }
        ExecuteDocumentRecordVo vo = new ExecuteDocumentRecordVo();
        BeanUtils.copyProperties(executeDocumentRecord, vo);
        return vo;
    }

    @Override
    public void updateDocumentSentInfo(String documentId, LocalDateTime sentTime, String sendStatus) {
        //更新文书送达截止日期
        if (ObjectUtils.isEmpty(documentId)) {
            throw new BusinessException("updateDocumentSentInfo-未指定文书id");
        }
        if (ObjectUtils.isEmpty(sendStatus)) {
            throw new BusinessException("updateDocumentSentInfo-未指定发送状态");
        }
        ExecuteDocumentRecord executeDocumentRecord = new ExecuteDocumentRecord();
        executeDocumentRecord.setSentTime(sentTime);
        String documentStatus = DocumentStatusEnum.WAIT_TO_SEND.getCode();
        if (DocumentSendStatusEnum.SEND_SUCCESS.getCode().equals(sendStatus)) {
            documentStatus = DocumentStatusEnum.SENT.getCode();
        }
        executeDocumentRecord.setDocumentSentStatus(documentStatus);
        Example updateExample = new Example(CaseDocumentRecord.class);
        updateExample.createCriteria().andEqualTo("id", documentId)
                //.andNotEqualTo("documentRecordStatus", DocumentRecordStatusEnum.WITHDRAW.getCode());
                .andIn("documentRecordStatus", Arrays.asList(DocumentRecordStatusEnum.NORMAL.getCode(), DocumentRecordStatusEnum.DRAFT.getCode()));
        executeDocumentRecordMapper.updateByExampleSelective(executeDocumentRecord, updateExample);
    }

    /**
     * 删除并添加历史
     *
     * @param
     * @return {@link int}
     * @author liyafeng
     * @date 2022/3/11
     */
    private int deleteAndSaveHis(List<ExecuteDocumentRecord> executeDocumentRecords) {
        int num = 0;
        //不为空，则添加历史，删除记录
        for (ExecuteDocumentRecord executeDocumentRecord : executeDocumentRecords) {
            //已审批完成的文书不删除
            if (!executeDocumentRecord.getDocumentApprovalStatus().equals(DocumentStatusEnum.CHECK_END.getCode())) {
                //添加历史
                ExecuteDocumentRecordHis docRecordHis = new ExecuteDocumentRecordHis();
                BeanUtils.copyProperties(executeDocumentRecord, docRecordHis);
                docRecordHis.setId(StringUtils.uuid());
                docRecordHis.setRecordId(executeDocumentRecord.getId());
                docRecordHis.setOp("delete");
                docRecordHis.setHisCreateTime(new Date());
                executeDocumentRecordHisMapper.insert(docRecordHis);
                //删除文书记录表
                num = executeDocumentRecordMapper.deleteByPrimaryKey(executeDocumentRecord.getId());
            }
        }
        return num;
    }
    /**
     * 描述：计算送达截止日期
     *
     * @param executeId              案件id
     * @param documentCatalogCode 文书目录编码
     * @param sendLimitDay        送达期限
     * @param sendLimitType       送达期限类型
     * @param isContainStartDay   是否包含开始日期
     * @return LocalDate 送达截止日期
     * @author xiangyuyu
     * @date 2022-03-04 09:41
     */
    @Override
    public LocalDate calculateSentDeadLine(String executeId, String documentCatalogCode, Integer sendLimitDay, String sendLimitType, boolean isContainStartDay) {
        LocalDate deadLine = null;
        //计算文书送达截止日期
        //开始计算时间
        LocalDateTime now = LocalDateTime.now();
        Integer day = sendLimitDay;
        if (!ObjectUtils.isEmpty(day)) {
            if (LimitDayTypeEnum.NATURE_DAY.getCode().equals(sendLimitType)) {
                deadLine = now.plusDays(day).toLocalDate();
            } else if (LimitDayTypeEnum.WORK_DAY.getCode().equals(sendLimitType)) {
                String startDate = now.toLocalDate().toString();
                ConfigEndDayQueryDto q = new ConfigEndDayQueryDto();
                q.setStartDate(startDate);
                q.setBeforeOrAfterSign(Constant.STRING_AFTER);
                q.setType(Constant.STRING_0);
                q.setDayCount(day);
                q.setIsContainStartDay(YesOrNoEnum.NO.getCode());
                deadLine = configWorkRestDayInfoService.getPeriodEndDate(q);
            } else {
                throw new BusinessException("非法送达期限类型(1-工作日/2-自然日)");
            }
        } else {
            //无截止日期限制
            logger.info("无截止日期限制 executeId:{} documentCatalogCode:{}", executeId, documentCatalogCode);
        }
        return deadLine;
    }
    @Override
    public ExecuteDocumentRecordDto getExecuteDocumentRecordByKindCode(String caseId, String documentKindCode) {
        return executeDocumentRecordMapper.selectExecuteDocumentRecordByKindCode(caseId, documentKindCode);
    }
}